<template>
  <!--分析报表-区域销售查询 -->
  <el-row style="height:100%">
    <page report="true">
      <div class="page-content report-con">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <h4 class="activeTitle">条件筛选：</h4>
            </template>
            <reportheader :reportState="'mall'"></reportheader>
          </el-collapse-item>
          <div class="timeoption">
            <label style="float: left; margin-right:10px;">导出报表：</label>
            <div class="exportBtn" v-show="timeSizeIsShow">
              <el-button-group class="exportBtn-el-button-group">
                <el-button type="primary" size="small" @click="TimeExport">导出分时报表</el-button>
                <el-button type="primary" size="small" @click="DistrExport">导出分布报表</el-button>
              </el-button-group>
            </div>
          </div>
          <div
            class='loadingClass'
            v-loading="xxloading"
            element-loading-text="请点击查询报表获取相关数据"
            element-loading-spinner="el-icon-caret-top"
            element-loading-background="rgba(245, 248, 254, 1)">
          <el-collapse-item name="2">
            <template slot="title">
              <h4 class="activeTitle">分时-合计报表：</h4>
            </template>
            <reportSaleCharts_timeAll  :kpislist="DataV.kpislist" :x_data="timeAllxData" :timeSize='timeSize' :con_w="con_w"
                                       :y_name="timeAllyName" :y_data="timeAllyData" ref='echartsTimeAll'
            ></reportSaleCharts_timeAll>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template slot="title">
              <h4 class="activeTitle">分时-分项报表：</h4>
            </template>
            <reportSaleCharts_timeSub :timeSubData="timeSubData" :y_data="timeSubYData" :x_data="timeAllxData" :kpislist="DataV.kpislist" :con_w="con_w"
                                      ref='echartsTimeSub'></reportSaleCharts_timeSub>
          </el-collapse-item>
          <el-collapse-item name="4">
            <template slot="title">
              <h4 class="activeTitle">分布-分项报表：</h4>
            </template>
            <reportSaleCharts_distrSub :DistrSubData="DistrSubData" :kpislist="DataV.kpislist" :con_w="con_w"
                                       ref='echartsDisterSub'></reportSaleCharts_distrSub>
          </el-collapse-item>
          </div>
        </el-collapse>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .loadingClass{
    .el-loading-mask{
      .el-loading-spinner{
        top: 80px;
        i{
          display: none;
        }
        .el-loading-text{
          font-size: 18px;
          font-weight: bold;
          color:#b4b6bd;
        }
      }
      
    }
  }
  .page-content {
    &.report-con {
      padding: 0 0;
    }

    padding: 15px;

    .fr {
      float: right;
    }

    .el-table {
      margin-bottom: 10px;
    }

    .paging {
      margin: 15px;
      height: 28px;
    }

    .hei13 {
      height: 15px;
      width: 100%;
    }
    .timeoption {
      margin: 0px 10px;
      height: 58px;
      .on {
        .el-input--suffix {
          .el-input__inner {
            color: #e8eeff;
            background: #5580ff;
          }
        }
      }
      margin-right: 60px;
      line-height: 48px;
      label {
        font-size: 18px;
        vertical-align: top;
      }
      .el-select {
        display: inline-block;
        margin-left: 5px;
        width: 72px;
        height: 30px;
        .el-input__inner {
          box-sizing: border-box;
          height: 32px;
          text-align: center;
          padding: 0 18px 0 0;
          width: 100%;
          font-size: 14px;
        }
        .el-input {
          position: relative;
          z-index: 9;
          .el-input__suffix {
            .el-input__suffix-inner {
              line-height: 100%;
              display: inline-block;
            }
            right: 0;
            span {
              .el-select__caret {
                font-size: 12px;
                color: #8ba9ff;
              }
            }
          }
        }
      }
      .timebtn-free {
        float: left;
        display: block;
        height: 100%;
        padding-top: 10px;
        //margin-left: -3px;
        a,
        .el-radio {
          border: 1px solid #dbe1e5;
          border-left: none;
          margin: 0 !important;
          float: left;
          height: 30px;
          line-height: 30px;
          color: #737373;
          font-size: 14px;
          padding: 0 18px;
          cursor: pointer;
          background: #fff;
          .el-radio__input {
            display: none;
          }
          .el-radio__label {
            padding: 0;
            line-height: 30px;
          }
          &.on,
          &.is-checked {
            color: #e8eeff !important;
            .el-radio__label {
              color: #e8eeff;
            }
            background: #5580ff !important;
          }
          &:first-child {
            border-left: 1px solid #dbe1e5;
            border-radius: 5px 0 0 5px;
          }
          &:last-child {
            border-radius: 0 5px 5px 0;
          }
          &:hover {
            background: #ebebeb;
            color: #333;
            opacity: 0.9;
          }
        }
        .el-radio-group{
          vertical-align: top;
        }
      }
      .exportBtn{
        display: inline-block;
        margin-left: 30px;
        height: 100%;
        padding-top: 10px;
        .exportBtn-el-button-group{
          vertical-align: top;
        }
      }
    }
  }
  .activeTitle{
    display: inline-block;
    margin: 5px 10px;
    font-size: 18px;
  }
  .el-collapse-item .el-collapse-item__header{
    border-bottom:1px solid rgba(220,220,220,0.5);
  }
  
</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import reportheader from "@/components/analyzeReport/reportpublic/reportFreeHead";
  import reportSaleCharts_timeAll from "@/components/analyzeReport/reportpublic/reportSaleCharts_timeAll";
  import reportSaleCharts_timeSub from "@/components/analyzeReport/reportpublic/reportSaleCharts_timeSub";
  import reportSaleCharts_distrSub from "@/components/analyzeReport/reportpublic/reportSaleCharts_distrSub";
  import reportGlobal from "@/components/global/reportGlobal";//公共配置
  import exportExcel from "@/components/global/exportExcel.js";//导出excel

  let unit = reportGlobal.unit;
  let kpiColor = reportGlobal.colorList;
  let kpiName = reportGlobal.name;
  export default {
    data: function () {
      return {
        activeNames:['1','2','3','4'],
        option: {
          shortcuts: 'dayShortcuts',
          isAreaShow: true,                 //是否显示区域，如显示需传title 默认不显示
        },
        DataV: {
          params:{},//获取数据参数
          start_day:'',//起始日期
          end_day:'',//终止日期
          start_hm:'',//起始时间
          end_hm:'',//终止时间
          kpislist:[],//选中的指标list
          tags:'',//选中的标签
          group_type:'',
        },      //head条件接收
        timeAllxData: [],//分时-合计数据
        timeAllyData: [],//分时-合计数据
        timeAllyName: [],//分时-合计数据

        timeSubData:[],//分时-分项数据
        timeSubYData:[],//分时-分项数据

        DistrSubData:[],//分布-分项数据

        TimeData: null,
        DistrData: null,

        timeSize:'',
        timeSizeIsShow:false,
        showDisabled: {
          sum: false,
          part: false,
        },
        echartKpis: [],//echart指标
        con_w:'',//组件宽度
        global: {},//公共参数
        code: this.$route.query.code,        //通过菜单栏点击传过来的code判断使用的公共参数
        xxloading:true,   //提示信息遮罩层
      };
    },
    components: {
      page,
      reportheader,
      reportSaleCharts_timeAll,
      reportSaleCharts_timeSub,
      reportSaleCharts_distrSub,
    },
    inject: ["reload"],
    created() {
      //根据code来获取公共参数
      for (let i in reportGlobal.queryList) {
        if (this.code == reportGlobal.queryList[i].code) {
          this.global = reportGlobal.queryList[i]
        }
      }
    },
    mounted() {
      //初始化触发事件
      setTimeout(() => {
        this.loadEchartResize();
      }, 200)
      //窗口变化触发事件
      setTimeout(() => {
        window.onresize = () => {
          this.loadEchartResize();
        };
      }, 200);
     //侧边栏菜单开关触发事件
      this.$Bus.$on("ArrowClick", w => {
        setTimeout(() => {
          this.loadEchartResize();
        }, 200)
      });
      //条件改变
      this.$Bus.$on("UpCondition", (params,datetimeval,KPI,tags,isDay,group_type) => {
        if(this.xxloading)
        {
          this.xxloading=false;
        }
        this.DataV.params = params;
        this.DataV.group_type = group_type
        this.DataV.start_day = datetimeval.day[0];
        this.DataV.end_day = datetimeval.day[1];
        this.DataV.start_hm = datetimeval.hm[0];
        this.DataV.end_hm = datetimeval.hm[1];
        this.DataV.kpislist = KPI;
        this.DataV.tags = tags;

        // console.log(this.DataV,'this.DataV');
        this.timeSize = isDay[0].tag
        this.timeSizeIsShow = isDay[0].type == 'MIN' ? false : true
        this.checkInterval()
      });
      //切换企业时清空数据
      this.$Bus.$on('Remove', () => {
        this.removedata(true);
      });
    },
    beforeDestroy() {
      window.onresize = null;
      this.$Bus.$off('UpCondition');
      this.$Bus.$off('Remove');
      this.$Bus.$off('ArrowClick');
    },
    watch: {
      TimeData(val){
        if(val && Object.keys(val).length){
          this.TimeSharing();
        }else{
          // this.$message.error('没有数据！')
        }
      },
      DistrData(val){
        if(val && Object.keys(val).length){
          this.Distribution();
        }else{
          // this.$message.error('没有数据！')
        }
      },
      //当route变化的时候，主要是报表之前传参
      $route(){
        this.reload()
      },
    },
    methods: {
      //颗粒度是否合法
      checkInterval(){
        let url = '/sys/report_assist_new/check_interval?interval=' + this.timeSize +
          "&start_day=" + this.DataV.start_day + "&end_day=" + this.DataV.end_day + "&start_hm=" + this.DataV.start_hm + "&end_hm=" + this.DataV.end_hm
        this.$api.post(url)
        .then(res=>{
          // console.log(res,'res');
          if(res == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(res.data){
            this.UpDataTime(true)
            this.UpDataDistr()
          }else{
            this.UpDataTime(false)
            this.UpDataDistr()
          }
        })
      },
      //分时数据
      UpDataTime(isSendTimeSize = true) {
        if (!Object.keys(this.DataV).length > 0) {
          this.removedata();
          this.$Bus.$emit("Loading", false);
          return
        }
        this.$Bus.$emit("Loading", true);
        let url = "/sys/report_new/time_division_sum?"
        url += "tags=" + this.DataV.tags + "&indicator_keys=" + this.DataV.kpislist + '&group_type=' + this.DataV.group_type;
        if (this.timeSize && isSendTimeSize) url += "&interval=" + this.timeSize;
        url += "&start_day=" + this.DataV.start_day + "&end_day=" + this.DataV.end_day + "&start_hm=" + this.DataV.start_hm + "&end_hm=" + this.DataV.end_hm;
        let params = this.DataV.params
        this.$api.post(url,params)
        .then(data => {
          // console.log(data.data);
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(data && data.data){
            if (data.data.item_list && data.data.item_list.length > 0) {
              this.TimeData = data.data;     //改变数据
            }else{
              console.log("区域下无数据");
              this.removedata();
            }
          }else{
            console.log("区域下无数据");
            this.removedata();
          }
          this.$Bus.$emit("Loading", false);
        })
        .catch(err => {
           console.log(err);
          this.removedata();
          this.$Bus.$emit("Loading", false);
        });
      },
      //分布数据
      UpDataDistr(){
        let url = "/sys/report_new/distribution_sum?"
        url += "tags=" + this.DataV.tags + "&indicator_keys=" + this.DataV.kpislist + '&group_type=' + this.DataV.group_type;
        url += "&start_day=" + this.DataV.start_day + "&end_day=" + this.DataV.end_day + "&start_hm=" + this.DataV.start_hm + "&end_hm=" + this.DataV.end_hm;
        let params = this.DataV.params
        // console.log(params,'params');
        this.$api.post(url,params)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(data && data.data){
            if (data.data.item_list && data.data.item_list.length > 0) {
              this.DistrData = data.data;     //改变数据
            }else{
              console.log("区域下无数据");
              this.removedata();
            }
          }else{
            console.log("区域下无数据");
            this.removedata();
          }
        })
        .catch(err => {
           console.log(err);
          this.removedata();
          this.$Bus.$emit("Loading", false);
        });
      },
      //分时 数据
      TimeSharing() {
        // console.log('TimeSharing');
        //配置分时合计参数
        let sum_list = this.TimeData.sum_list
        let showKpislist = this.DataV.kpislist;
        let timeAllx_data = [];
        let timeAlly_data = {};
        let timeAlly_name = {};
        for(let kpi in showKpislist){
          timeAlly_data[showKpislist[kpi]] = []
        }
        //数据转换成echarts需要数据
        for (let i = 0; i < sum_list.length; i++) {
          for(let kpi in showKpislist){
            timeAlly_data[showKpislist[kpi]].push(sum_list[i][showKpislist[kpi]]);
          }
          timeAllx_data.push(sum_list[i].time_tag)
        }
        for(let kpi in showKpislist){
          timeAlly_name[showKpislist[kpi]] = "全部-"+ kpiName[showKpislist[kpi]];
        }
        //得到新数据改变echarts数据
        this.timeAllxData = [...new Set(timeAllx_data)];//['00:00','01:00','02:00']
        this.timeAllyName = timeAlly_name;//['全部-进入人数','全部-离开人数']
        this.timeAllyData = timeAlly_data;//{enters:[],exits:[]}
        this.$nextTick(() => {
          this.$refs.echartsTimeAll.UpData(true);
        })

        //配置分时分项参数
        let item_list = this.TimeData.item_list
        // console.log(item_list,'item_list');
        let timeSubData = {}
        let timeSubYData = {}
        for(let i in showKpislist){
          timeSubData[showKpislist[i]] = []
          timeSubYData[showKpislist[i]] = {}
        }
        for(let i in showKpislist){
          for(let j in item_list){
            let obj = {name:'',value:''}
            let name = this.DataV.group_type == 'company' ? 'company_name' :
              this.DataV.group_type == 'case' ? 'case_info_name' :
              this.DataV.group_type == 'area' ? 'area_name' : 'tag_name'

            obj.name = item_list[j][name];
            obj.value = item_list[j][showKpislist[i]];
            timeSubData[showKpislist[i]].push(obj)
            if(timeSubYData[showKpislist[i]][item_list[j][name]]){
              timeSubYData[showKpislist[i]][item_list[j][name]] += item_list[j][showKpislist[i]] ? item_list[j][showKpislist[i]] + ',' : 'null,'
            }else{
              timeSubYData[showKpislist[i]][item_list[j][name]] = item_list[j][showKpislist[i]] ? item_list[j][showKpislist[i]] + ',' : 'null,'
            }
          }
        }
        for(let i in timeSubYData){
          for(let j in timeSubYData[i]){
            timeSubYData[i][j] = timeSubYData[i][j].split(',')
            timeSubYData[i][j].splice(-1,1)
            timeSubYData[i][j] = timeSubYData[i][j].map(x=>{
              if(x == 'null') x = null
              return x
            })
          }
        }
        this.timeSubData = timeSubData
        this.timeSubYData = timeSubYData
        this.$nextTick(() => {
          this.$refs.echartsTimeSub.UpData(true);
        })
        this.$Bus.$emit("Loading", false);
      },
      //分布 数据
      Distribution(){
        // console.log(this.DataV,'this.DataV');
        let showKpislist = this.DataV.kpislist;
        let item_list = this.DistrData.item_list
        let timeSubData = {}
        // console.log(item_list,'item_list');
        for(let i in showKpislist){
          timeSubData[showKpislist[i]] = []
        }
        for(let i in showKpislist){
          for(let j in item_list){
            let obj = {name:'',value:''}
            let name = this.DataV.group_type == 'company' ? 'company_name' :
              this.DataV.group_type == 'case' ? 'case_info_name' :
                this.DataV.group_type == 'area' ? 'area_name' : 'tag_name'

            obj.name = item_list[j][name];
            obj.value = item_list[j][showKpislist[i]];
            timeSubData[showKpislist[i]].push(obj)
          }
        }
        this.DistrSubData = timeSubData

        this.$nextTick(() => {
          this.$refs.echartsDisterSub.UpData(true);
        })
        this.$Bus.$emit("Loading", false);
      },
      //清除数据
      removedata(iscomp=false) {
        this.$refs.echartsTimeAll.UpData(false);
        this.$refs.echartsDisterSub.UpData(false);
        this.$refs.echartsTimeSub.UpData(false);
        this.TimeData = null;
        this.DistrData = null;
        if(iscomp)
          this.DataV = {};
      },
      timegranuChange(){
        if(Object.keys(this.DataV).length==0){
          this.$message.warning('参数有误，请检查选择条件！')
          this.$Bus.$emit('Loading',false)
          return
        }
        this.checkInterval();
      },
      //
      loadEchartResize(){
        this.con_w = $(".page-content").width() - 45
      },

      //导出分时报表
      TimeExport(){
        // console.log(this.DataV,'this.DataV');
        // console.log(this.TimeData,'this.TimeData');
        // console.log(this.DataV.kpislist,'this.DataV.kpislist');
        let Array = [];
        let tableHeader = '时间,名称';
        let tableName = '分时数据统计报表' + this.DataV.start_day + '-' + this.DataV.end_day
        let item_list = this.TimeData.item_list
        let kpislist = this.DataV.kpislist
        for(let i in kpislist){
          tableHeader += ','+ kpiName[kpislist[i]] + '(' + unit[kpislist[i]] + ')'
        }
        for(let i in item_list){
          let obj = {}
          obj.time = item_list[i].time_tag ? item_list[i].time_tag : ''
          obj.name = this.DataV.group_type == 'company' ? item_list[i].company_name :
            this.DataV.group_type == 'case' ? item_list[i].case_info_name :
              this.DataV.group_type == 'area' ? item_list[i].case_info_name : item_list[i].tag_name;

          for(let ii in kpislist){
            obj[kpislist[ii]] = item_list[i][kpislist[ii]] != null  ? item_list[i][kpislist[ii]] : ''
          }
          Array.push(obj)
        }



        exportExcel.tableToExcel(Array,tableHeader,tableName);
      },
      //导出分布报表
      DistrExport(){
        let Array = [];
        let tableHeader = '名称';
        let tableName = '分布数据统计报表'+ this.DataV.start_day + '-' + this.DataV.end_day
        let item_list = this.DistrData.item_list
        let kpislist = this.DataV.kpislist
        for(let i in kpislist){
          tableHeader += ','+ kpiName[kpislist[i]] + '(' + unit[kpislist[i]] + ')'
        }
        for(let i in item_list){
          let obj = {}
          obj.name = this.DataV.group_type == 'company' ? item_list[i].company_name :
            this.DataV.group_type == 'case' ? item_list[i].case_info_name :
            this.DataV.group_type == 'area' ? item_list[i].case_info_name : item_list[i].tag_name;

          for(let ii in kpislist){
            obj[kpislist[ii]] = item_list[i][kpislist[ii]] != null  ? item_list[i][kpislist[ii]] : ''
          }
          Array.push(obj)
        }
        exportExcel.tableToExcel(Array,tableHeader,tableName);
      }
    }
  };
</script>
